from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from .models import Classification, Commodity, CommodityImg


# 分类序列化器
class ClassificationsSerializer(ModelSerializer):
    class Meta:
        model = Classification
        fields = ['id', 'name']


# 一级分类序列化器
class ParentClassificationsSerializer(ModelSerializer):
    # 一级分类要展示的所有子分类
    classification_set = ClassificationsSerializer(many=True, read_only=True)

    class Meta:
        model = Classification
        fields = ['id', 'name', 'classification_set']


# 商品图片序列化器
class CommodityImgSerializer(ModelSerializer):
    class Meta:
        model = CommodityImg
        fields = "__all__"

        extra_kwargs = {
            "priority": {"read_only": True},
        }


class CommodityImgSerializerSimple(ModelSerializer):
    class Meta:
        model = CommodityImg
        exclude = ["created_time", "updated_time", "is_delete", "commodity", "priority"]

        extra_kwargs = {
            "priority": {"read_only": True},
        }


class CommoditySerializer(ModelSerializer):
    # 一级分类
    classification1_name = serializers.CharField(source='classification1.name', read_only=True)
    classification2_name = serializers.CharField(source='classification2.name', read_only=True)
    # 二级分类
    commodityimg_set = CommodityImgSerializerSimple(many=True, read_only=True)

    class Meta:
        model = Commodity
        exclude = ['is_delete']
        extra_kwargs = {
            'sales': {'read_only': True},
            'comments': {'read_only': True},
        }
